import axios from "axios"
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from "axios"
import { message } from "antd"

// 创建 axios 实例
const instance: AxiosInstance = axios.create({
  baseURL: process.env.REACT_APP_API_URL || "http://localhost:3001",
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
})

// 请求拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 在这里可以添加认证信息等
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response

    // 这里可以根据后端的响应结构进行适配
    if (data.code === 0) {
      return data.data
    }

    return response.data
  },
  (error) => {
    if (error.response) {
      const { status, data } = error.response

      switch (status) {
        case 400:
          message.error(data.message || "请求参数错误")
          break
        case 401:
          message.error("未授权，请重新登录")
          // 这里可以处理登录过期的逻辑
          break
        case 403:
          message.error("拒绝访问")
          break
        case 404:
          message.error("请求的资源不存在")
          break
        case 500:
          message.error("服务器错误")
          break
        default:
          message.error("网络错误")
      }
    } else if (error.request) {
      message.error("网络连接失败，请检查网络")
    } else {
      message.error("请求配置错误")
    }

    return Promise.reject(error)
  },
)

export const request = {
  get: <T = any>(url: string, config?: InternalAxiosRequestConfig) => instance.get<T>(url, config),

  post: <T = any>(url: string, data?: any, config?: InternalAxiosRequestConfig) => instance.post<T>(url, data, config),

  put: <T = any>(url: string, data?: any, config?: InternalAxiosRequestConfig) => instance.put<T>(url, data, config),

  delete: <T = any>(url: string, config?: InternalAxiosRequestConfig) => instance.delete<T>(url, config),

  patch: <T = any>(url: string, data?: any, config?: InternalAxiosRequestConfig) =>
    instance.patch<T>(url, data, config),
}
